import Taro from '@tarojs/taro';

import { Command } from '../constant';
import { Dispatch } from 'typings';
import { IAllReducerProps } from '../types';
import { getReducerData } from '@/redux/store';
import { extraPathsValue } from '@/redux/util';

import api from 'api';

export default (dispatch: Dispatch) => {
  let action = {
    commonChange(...param: any) {
      dispatch({
        type: Command.commonChange,
        payload: extraPathsValue(...arguments),
      });
    },

    async query() {
      let list = await api.customerDeliveryAddressController.findAddressList();
      if (list.length > 0) {
        // 省、市、区（县）、街道（乡）+ 详细地址
        list.map((item) => {
          item['addressInfo'] = `${item.provinceName || ''}${item.cityName || ''}${item.areaName ||
            ''}${item.streetName || ''}${item.deliveryAddress || ''}`;
        });
        action.commonChange('main.addressList', list)
      } else {
        action.commonChange('main.addressList', [])
      }
    },

    /**
     * 删除收货地址
     */
    async deleteAddress(addressId: string) {
      try {
        await api.customerDeliveryAddressController.deleteAddress(addressId);
        Taro.showToast({
          title: '删除成功',
          icon: 'none',
          duration: 2000,
        });
        action.query();
      } catch (e) { }
    },
    /**
     * 设为默认收货地址
     */
    async setDefault(addressId: string) {
      try {
        await api.customerDeliveryAddressController.setDefaultAddress(addressId);
        Taro.showToast({
          title: '设置成功！',
          icon: 'none',
          duration: 2000,
        });
        action.query();
      } catch (e) {}
    },
  };
  return action;
};

function getData(): IAllReducerProps {
  return {
    main: getReducerData('packageAddressSelectDMain'),
  };
}
